package com.bb.blog.code.zk;

import com.alibaba.fastjson.JSONObject;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * 性能监视器(简略版)
 */
public class ZkMonitor extends ZkClient {

    private static Logger logger = LoggerFactory.getLogger(ZkMonitor.class);
    private static String rootPath = "/monitor";
    private static String servicePath = rootPath + "/service";
    private String nodePath;
    private Thread stateThread;

    public ZkMonitor (){
        super();
        init();


    }

    public void init(){
        try {
            createRootNode();
            stateThread = new Thread(()->{
               while(true){
                   try {
                       createServiceNode();
                       Thread.sleep(5000);
                   } catch (InterruptedException | KeeperException e) {
                       logger.info("运行异常",e);
                   }
               }
            },"zk_stateThread");
            stateThread.setDaemon(true);
            stateThread.start();

        } catch (InterruptedException | KeeperException e) {
          logger.info("初始化异常",e);
        }
    }


    protected void  createRootNode() throws InterruptedException, KeeperException {
        if (zk.exists(rootPath, true) == null) {
            zk.create(rootPath,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    }

    protected void createServiceNode() throws InterruptedException, KeeperException {
        byte[] data = getOsData();
        if(zk.exists(servicePath, true) == null ){
            zk.create(servicePath, getOsData(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
        }
    }

    private byte[] getOsData() {
        JSONObject os = new JSONObject();
        long ts = System.currentTimeMillis();

        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            String ip = inetAddress.getHostAddress();
            os.put("ip", ip);
        } catch (UnknownHostException e) {
            logger.error("获取ip出现异常", e);
        }

        int kb = 1024;
        long totalMemory = Runtime.getRuntime().totalMemory() / 1024;
        long freeMemory = Runtime.getRuntime().freeMemory() / 1024;
        long maxMemory = Runtime.getRuntime().maxMemory() / 1024;

        os.put("ts", ts);
        os.put("totalMemory", totalMemory);
        os.put("freeMemory", freeMemory);
        os.put("maxMemory", maxMemory);

        return os.toJSONString().getBytes(StandardCharsets.UTF_8);
    }

    public void watch(){
        try {
            zk.getChildren(rootPath,(e)->{
                System.out.println(e);

            });
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ZkMonitor zkMonitor = new ZkMonitor();
        Thread.sleep(100000000);
    }

}
